//index.js
const app = getApp()
const config = require('../../config')
const timeUtil = require('../../utils/timeUtil')
const env = require('../../env')
const restService = require('../../services/restService')
const util = require('../../utils/util')
const rsa = require('../../utils/rsaUtl')
const aes = require('../../utils/aesUtil')

Page({
  data: {
    clock: [],
    isLoadingBanner: true,
    imageUrl: config.url.images,
    swiperCurrent: 0,
    userInfo: {},
    requestResult: '',
    isShowResigterModal: true,
    isLoading: true,
    moduleList: [],
    experiences: []
  },

  onPullDownRefresh: function () {
    wx.request({
      url: '',
      data: {},
      method: 'GET',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) {
        wx.stopPullDownRefresh();
      }
    })
  },

  onLoad: function() {
    console.log("index-onload===========")
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    // 获取用户信息
    // 查看是否授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: (res) => {
              console.log(res.userInfo)
              this.setData({
                isShowResigterModal: false,
              })
            },
            fail: function() {
              console.error("getUserInfo error")
            }
          })
        }else {
          this.setData({
            isShowResigterModal: true,
          })
        }
      }
    })

    var interval = setInterval(function () {
      //将时间传如 调用
      let examTime = '2024/01/18 00:00:00';
      
      var clock = timeUtil.calculateTime(examTime.replace(/-/g, '/'));
      var desc = '距离2024年1月18日剩余：'+clock;
      this.setData({//正常倒计时        
        clock: desc
      });
    }.bind(this), 1000);
  },
  onGetUserInfo: function(e) {
    console.log("onGetUserInfo========="+e.detail.userInfo)
    if (!this.logged && e.detail.userInfo) {
      console.log("onGetUserInfo=========1")
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo,
      })
      this.createMember(e.detail.userInfo)
    }
  },
  getPhoneNumber: function(e) { 
    console.log(e.detail.errMsg) 
    console.log(e.detail.iv) //包括敏感数据在内的完整用户信息的加密数据,需要解密
    console.log(e.detail.encryptedData) //加密算法的初始向量，解密需要用到
    wx.login({
     success: res => {
      if(res.code){
        console.log(res.code)
      }
     }
    })
  },

  createMember: function (user) {
    // 创建会员
    console.log("创建会员")
  },

  getMember: function () {
    // 查询会员
    console.log("查询会员");
  },

  onGetOpenid: function () {
    // 调用云函数
    // wx.cloud.callFunction({
    //   name: 'login',
    //   data: {},
    //   success: res => {
    //     openid = res.result.openid
    //     console.log('[云函数] [login] user openid: ', openid)
    //     app.globalData.openid = openid
    //   },
    //   fail: err => {
    //     console.error('[云函数] [login] 调用失败', err)
    //   }
    // })
  },

  /**
    * 生命周期函数--监听页面显示
    */
  onShow: function () {
    this.setData({
      selectedStatus: true, // 底部菜单选中状态
    })
    this.getBanner()
    this.getExperience()
    this.getModuleList()
    this.setData({
      isLoadingBanner: false, // 底部菜单选中状态
      isLoading: false
    })
  },

  onShareAppMessage() {
    // return custom share data when user share.
  },

  getBanner: function () {
    restService.commonRequest({
      url: config.service.getBanner,
      data: {
        location: "0"
      },
      method: 'POST',
      success: res => {
        let banners = []
        for (let item of res.data) {
          banners.push({
            bannerUrl: item.url,
            title: item.title,
            pagePath: item.link
          })
        }
        this.setData({
          banners: banners,
          isLoadingBanner: false
        })
      },
      fail: err => {
        console.log(err, 'error')
      }
    })
  },

  getExperience: function () {
    restService.commonRequest({
      url: config.service.getBanner,
      data: {
        location: "1"
      },
      method: 'POST',
      success: res => {
        let experiences = []
        for (let item of res.data) {
          experiences.push({
            cover: item.url,
            title: item.title,
            pagePath: item.link
          })
        }
        this.setData({
          experiences: experiences,
          isMoreBabyPlay: true
        });
      },
      fail: err => {
        console.log(err, 'error')
      }
    })
  },

  getModuleList: function () {
    restService.commonRequest({
      url: config.service.getStudyModuleList,
      data: {
        test: "123"
      },
      method: 'POST',
      success: res => {
        var responseD = this.formatModuleList(res.data)
          this.setData({
            moduleList: responseD
          });
      },
      fail: err => {
        console.log(err, 'error')
      }
    })
    // restService.post(config.service.getStudyModuleList,studyModule).then((res) => {
    //   if (res && res.statusCode == 200) {
    //     const resp = JSON.parse(res.data)
    //     if (resp && resp.code == 0) {
    //       var array = aes.decrypt(rsa.decrypt(resp.randomKey),resp.data)
    //       var responseD = this.formatModuleList(array)
    //       this.setData({
    //         moduleList: responseD
    //       })
    //     } 
    //   }
    // }).catch((res) => {
    //   util.logAndTips("index2:", "getModuleList3:", res)
    // })
    // return null
  },
  formatModuleList: function (studyModuleList) {
    let formatedSummaryList = []
    for (let item of studyModuleList) {
      formatedSummaryList.push({
        id: item.moduleCode,
        imageUrl: item.coverPicture ? item.coverPicture : "../../images/index/index_answer.png",
        title: item.moduleName,
        subTitle: item.moduleDesc ? item.moduleDesc : ''
      })
    }
    return formatedSummaryList
  },

  add: function () {
    wx.cloud.callFunction({
      // 云函数名称
      name: 'add',
      // 传给云函数的参数
      data: {
        a: 1,
        b: 2,
      },
    })
      .then(res => {
        console.log(res.result) // 3
      })
      .catch(console.error)
  },

  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  toBannerPage: function (e){
    if (e.currentTarget.dataset.item.pagePath){
      wx.navigateTo({
        url: config.pages.webview + '?url=' + e.currentTarget.dataset.item.pagePath,
      })
    }
  }
})
